#!/bin/bash

# 版本信息API测试脚本
# 用于测试新创建的版本信息API

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

echo -e "${BLUE}=========================================="
echo "零售中台系统 版本信息API 测试脚本"
echo "=========================================="

# 基础URL配置
BASE_URL="http://localhost:9080/retail-admin"

# 测试函数
test_api() {
    local method=$1
    local url=$2
    local data=$3
    local description=$4
    
    echo -e "\n${YELLOW}测试: $description${NC}"
    echo "请求: $method $url"
    
    if [ -n "$data" ]; then
        response=$(curl -s -w "\n%{http_code}" -X "$method" \
            -H "Content-Type: application/json" \
            -d "$data" \
            "$url")
    else
        response=$(curl -s -w "\n%{http_code}" -X "$method" \
            -H "Content-Type: application/json" \
            "$url")
    fi
    
    # 分离响应体和HTTP状态码
    response_body=$(echo "$response" | sed '$d')
    http_code=$(echo "$response" | tail -n1)
    
    if [ "$http_code" -eq 200 ]; then
        echo -e "${GREEN}✓ 成功 (HTTP $http_code)${NC}"
        echo "响应: $response_body"
        
        # 验证响应内容
        if echo "$response_body" | grep -q '"success":true'; then
            echo -e "${GREEN}✓ 响应格式正确${NC}"
        else
            echo -e "${RED}✗ 响应格式错误${NC}"
        fi
    else
        echo -e "${RED}✗ 失败 (HTTP $http_code)${NC}"
        echo "响应: $response_body"
    fi
}

# 检查服务状态
echo -e "${YELLOW}检查服务状态...${NC}"

if curl -s http://localhost:9080/retail-admin/api/version > /dev/null; then
    echo -e "${GREEN}✓ 后端应用运行中 (端口9080)${NC}"
else
    echo -e "${RED}✗ 后端应用未运行，请先启动应用${NC}"
    echo "运行命令: cd backend/retail-admin && mvn spring-boot:run -Dspring-boot.run.arguments=\"--server.port=9080\""
    exit 1
fi

# 等待服务完全启动
echo -e "${YELLOW}等待服务完全启动...${NC}"
sleep 5

echo -e "\n${BLUE}开始版本信息API测试...${NC}"

# 1. 测试获取版本信息
test_api "GET" "$BASE_URL/api/version" "" "获取版本信息"

# 2. 测试健康检查API
test_api "GET" "$BASE_URL/api/version/health" "" "健康检查API"

# 3. 测试基础健康检查
test_api "GET" "$BASE_URL/" "" "基础健康检查"

# 4. 测试API文档访问
test_api "GET" "$BASE_URL/doc.html" "" "API文档访问"

echo -e "\n${BLUE}=========================================="
echo "版本信息API 测试完成"
echo "=========================================="
echo "服务地址："
echo "  后端API: http://localhost:9080/retail-admin/"
echo "  版本信息: http://localhost:9080/retail-admin/api/version"
echo "  健康检查: http://localhost:9080/retail-admin/api/version/health"
echo "  API文档: http://localhost:9080/retail-admin/doc.html"
echo "=========================================="

